package indi.zhifa.learn.jenkins.helloworld2.web.config;

import indi.zhifa.learn.jenkins.helloworld2.common.entity.ServiceException;
import indi.zhifa.learn.jenkins.helloworld2.web.appconfig.AppConfig;
import indi.zhifa.learn.jenkins.helloworld2.web.appconfig.minio.MinioProperty;
import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author hatak
 */
@Configuration
@AllArgsConstructor
public class MinioConfig {

    final AppConfig appConfig;

    @Bean
    public MinioClient getMinioClient(){
        MinioProperty minioProperty = appConfig.getMinio();
        MinioClient minioClient =MinioClient.builder()
                .endpoint(minioProperty.getEndpoint())
                .credentials(minioProperty.getAccessKey(),minioProperty.getSecretKey()).build();
        try{
            boolean exist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperty.getBucketName()).build());
            if(!exist){
                throw new ServiceException("没有找到名为【"+minioProperty.getBucketName()+"】的bucket");
            }
        }catch (Exception ex){
            throw new ServiceException("创建客户端发生错误，错误信息是 "+ex.toString());
        }

        return minioClient;
    }
}
